import requests
import sys
import json

def get_ip_info(ip_address):
    """
    使用免费的IP-API服务获取IP地址的地理位置信息
    
    参数:
        ip_address (str): 要查询的IP地址
        
    返回:
        dict: 包含IP地址地理位置信息的字典
    """
    url = f"http://ip-api.com/json/{ip_address}?fields=status,message,country,regionName,city,district,zip,lat,lon,isp,org,as,mobile,proxy,hosting"
    
    try:
        response = requests.get(url)
        data = response.json()
        
        if data["status"] == "success":
            return data
        else:
            return {"error": data.get("message", "未知错误")}
    except Exception as e:
        return {"error": str(e)}

def format_ip_info(ip_info, ip_address):
    """
    格式化IP地址信息
    
    参数:
        ip_info (dict): IP地址信息字典
        
    返回:
        str: 格式化后的IP地址信息
    """
    if "error" in ip_info:
        return f"查询失败: {ip_info['error']}"
    
    result = [ 
        f"IP地址: {ip_address}",
        f"国家/地区: {ip_info.get('country', '未知')}",
        f"省/州: {ip_info.get('regionName', '未知')}",
        f"城市: {ip_info.get('city', '未知')}"
    ]
    
    # 添加更详细的本地信息
    if ip_info.get('district'):
        result.append(f"区域: {ip_info['district']}")
    
    if ip_info.get('zip'):
        result.append(f"邮政编码: {ip_info['zip']}")
    
    # 添加坐标信息
    if ip_info.get('lat') and ip_info.get('lon'):
        result.append(f"经纬度: {ip_info['lat']}, {ip_info['lon']}")
    
    # 添加ISP信息
    if ip_info.get('isp'):
        result.append(f"ISP提供商: {ip_info['isp']}")
    
    if ip_info.get('org'):
        result.append(f"组织: {ip_info['org']}")
    
    if ip_info.get('as'):
        result.append(f"AS编号: {ip_info['as']}")
    
    # 添加其他信息
    if ip_info.get('mobile') == True:
        result.append("移动网络: 是")
    
    if ip_info.get('proxy') == True:
        result.append("代理: 是")
    
    if ip_info.get('hosting') == True:
        result.append("托管服务: 是")
    
    return "\n".join(result)

def batch_process_ip(ip_file):
    """
    批量处理IP地址文件
    
    参数:
        ip_file (str): IP地址文件路径
        
    返回:
        list: 包含每个IP地址信息的列表
    """
    results = []
    try:
        with open(ip_file, 'r') as file:
            for line in file:
                ip = line.strip()
                if ip:
                    ip_info = get_ip_info(ip)
                    results.append({
                        "ip": ip,
                        "info": ip_info
                    })
        return results
    except Exception as e:
        print(f"读取文件失败: {str(e)}")
        return []

if __name__ == "__main__":
    if len(sys.argv) == 2:
        ip_address = sys.argv[1]
        
        # 检查是否为文件路径
        if ip_address.endswith('.txt'):
            results = batch_process_ip(ip_address)
            for result in results:
                print(format_ip_info(result["info"], result["ip"]))
                print("-" * 50)
        else:
            # 单个IP地址处理
            ip_info = get_ip_info(ip_address)
            print(format_ip_info(ip_info, ip_address))
    else:
        print("使用方法:")
        print("1. 查询单个IP: python ip_lookup.py 8.8.8.8")
        print("2. 批量查询: python ip_lookup.py ip_list.txt")
        
        # 交互式输入
        ip_address = input("请输入要查询的IP地址: ")
        if ip_address:
            ip_info = get_ip_info(ip_address)
            print(format_ip_info(ip_info, ip_address))
